#Python's module
Modules are the basic unit of Python program organization, which organizes related code together. Simply put, a .py
file is a module.
#Import of modules
To import a module in Python, use the import
keyword:
import module-name # Import module
from module-nam import name-list # Importing partial names from a module
For example:
import os # Import the os module, which provides operating system related interfaces
from math import pi # Import pi from the math module
print(os.name)
print(pi)
#Common forms of modules
Modules mainly include file and directory:
- A file module ends with
.py
and the module name is the file name (without.py
). - A directory module needs to contain a
__init__.py
file with the module name being the directory name.
When you import a directory module, you actually import the __init__.py
file in it, so you usually need to import other files in the directory in __init__.py
.
For example, the file structure is as follows:
src/ ├── main.py └── utils/ ├── __init__.py ├── helper.py └── config.py
To import directly from utils
, you need to write the following in __init__.py
:
# __init__.py
from .helper import *
from .config import *
The
.
at the beginning of the module name here refers to the current directory (the directory where the current file__init__.py
is located).*
imports all names.
For example:
# utils/__init__.py
from .helper import *
from .config import *
# utils/helper.py
def help():
print('help message')
# main.py
from utils import help # Import the help function directly without going through helper
help()
You can also import other files in the directory by import directory name.file name
(for example, import utils.helper
or from utils import helper
).
In this case, __init__.py
does not need to have any content. For example:
import utils.helper
from utils import helper
#__name__
Each module has an implicit variable __name__
:
- If the module is imported, the value of
__name__
is the module name - If the module is run directly (
python xxx.py
), the value of__name__
is__main__
.
When a module is first imported into a program, the code in it is executed.
You can use __name__
to prevent some code from being executed when it is imported, but only when it is directly run.
if __name__ == "__main__":
# code to execute
pass
#Standard library modules
Python comes with many built-in modules, called standard library modules, which can be directly imported and used without additional installation. Please refer to API Help Manual - Built-in Modules.
#Third party package
Python has a large number of third-party packages that can be installed through the pip
command.
pip install package-name
After installation, you can use the modules in the package.